// https://leetcode.cn/problems/linked-list-components/
// Created by ade on 2022/10/12.
//

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
#include <iostream>
#include <unordered_map>
#include <algorithm>

using namespace std;

class Solution {
public:
    int numComponents1(ListNode *head, vector<int> &nums) {
        int i = 0;
        unordered_map<int, int> m = {};
        while (head) {
            m[head->val] = i++;
            head = head->next;
        }
        for (int i = 0; i < nums.size(); i++) {
            nums[i] = m[nums[i]];
        }
        sort(nums.begin(), nums.end());
        int count = 1;
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] - nums[i - 1] != 1) {
                count++;
            }
        }
        return count;
    }

    int numComponents(ListNode *head, vector<int> &nums) {
        unordered_map<int, int> m = {};
        for (int i = 0; i < nums.size(); i++) {
            m[nums[i]] = 1;
        }
        int count = 0;
        while (head) {
            if (m.find(head->val) != m.end()) {
                while (head->next && m.find(head->next->val) != m.end()) {
                    head = head->next;
                }
                head = head->next;
                count++;
            } else {
                head = head->next;
            }
        }
        return count;
    }
};